import React, { useState, useEffect } from 'react';
import axios from 'axios';
import DataTable from 'react-data-table-component';
import { Dialog, DialogTitle, DialogContent, Button } from '@mui/material';
import AddEquipmentDialog from './AddEquipmentDialog'; 
import AddSensorDialog from './AddSensorDialog'; 
import { paginationComponentOptions, customTableStyles } from '../Constants';
import "./Feeding.css"
import { useNavigate } from 'react-router-dom';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faArrowLeft } from '@fortawesome/free-solid-svg-icons';

const EquipmentPage = () => {
    const [equipment, setEquipment] = useState([]);
    const [sensors, setSensors] = useState([]);
    const [openEquipDialog, setOpenEquipDialog] = useState(false);
    const [openSensorDialog, setOpenSensorDialog] = useState(false);
    const [equipmentId, setEquipmentId] = useState(0);
    const navigate = useNavigate();

  const goBack = () => {
    navigate('/home')
  };

    useEffect(() => {
        fetchData();
        fetchSensors()
    }, []);

    useEffect(() => {
        fetchSensors();
    }, [equipmentId]);

    const fetchSensors = async () => {
        try {
            console.log(equipmentId)
            const headers = {
                'Authorization': `Bearer ${localStorage.getItem('access')}`,
            };
            const response = await axios.get(`${process.env.REACT_APP_API_BASE_URL}/sensors${equipmentId!= 0? "?equipment="+equipmentId:""}`, {headers});
            setSensors(response.data.sensors);
        } catch (error) {
            console.error('Error fetching sensors:', error);
        }
    };

    const fetchData = async () => {
        try {
            const headers = {
                'Authorization': `Bearer ${localStorage.getItem('access')}`,
            };
            const equipmentResponse = await axios.get(`${process.env.REACT_APP_API_BASE_URL}/equipment`, {headers});
            setEquipment(equipmentResponse.data.equipments);

        } catch (error) {
            console.error('Error fetching data:', error);
        }
    };

    const handleOpenEquipDialog = () => {
        setOpenEquipDialog(true);
    };

    const handleCloseEquipDialog = () => {
        setOpenEquipDialog(false);
    };

    const handleOpenSensorDialog = () => {
        setOpenSensorDialog(true);
    };

    const handleCloseSensorDialog = () => {
        setOpenSensorDialog(false);
    };

    const sensorsColumns = [
        { name: 'Название', selector: row => row.name, wrap: true, width: "200px", },
        { name: 'Местоположение', selector: row => row.location, wrap: true },
        { name: 'Мин. рабочее\n состояние', selector: row => row.min_operating_condition, wrap: true, style: {} },
        { name: 'Макс. рабочее состояние', selector: row => row.max_operating_condition },
        { name: 'Мин. критическое состояние', selector: row => row.min_critical_condition },
        { name: 'Макс. критическое состояние', selector: row => row.max_critical_condition },
        { name: 'Мин. фатальное состояние', selector: row => row.min_fatal_condition },
        { name: 'Макс. фатальное состояние', selector: row => row.max_fatal_condition },
        { name: 'Единицы измерения', selector: row => row.units, wrap: true },
        { name: 'Частота измерений', selector: row => row.frequency +" раз " + row.dimension },
        { name: 'Вкл/Выкл', selector: row => row.on_off ? "Вкл" : "Выкл" },
        { name: 'ID оборудования', selector: row => row.id_equipment }
    ];

    const equipmentColumns = [
        { name: 'Номер', selector: row => row.code },
        { name: 'Название', selector: row => row.ename },
        { name: 'Режим', selector: row => row.mname },
        { name: 'Тип', selector: row => row.tname },
        { name: 'Подтип', selector: row => row.name },
        { name: 'Включено', selector: row => row.off?"Подключено":"Отключено" },
        { name: 'Доп.информация', selector: row => row.comment },

    ];

    const handleEquipmentChange = (event) => {
        setEquipmentId(event.target.value);
    };


    return (
        <div style={{ padding: 30 }}>
             <button onClick={goBack}>
        <FontAwesomeIcon icon={faArrowLeft} /> Главное меню
      </button>
            <div className="header" style={{ marginBottom: 50 }}>
                <div className="left">
                    <h1 style={{ paddingLeft: '20px', fontWeight: 'normal' }}>Оборудование</h1>
                </div>
                <div className="right">
                    <button onClick={handleOpenEquipDialog}>Добавить новое оборудование</button>
                </div>
                <div className="right">
                    <button onClick={handleOpenSensorDialog}>Добавить новый датчик</button>
                </div>
            </div>
            <DataTable
                columns={equipmentColumns}
                data={equipment}
                pagination
                defaultSortFieldId={1}
                paginationComponentOptions={paginationComponentOptions}
                customStyles={customTableStyles}
                title={'Оборудование'}
            />
            <select
                value={equipmentId}
                onChange={handleEquipmentChange}
                style={{ borderColor: '#003AD0', margin: 0, width: '100%', paddingBlock: 5  }}
            >
                <option value={0}>Выберите оборудование</option>
                {equipment.map(sensor => (
                    <option key={sensor.eid} value={sensor.eid}>{sensor.ename}</option>
                ))}
            </select>
            <DataTable
                columns={sensorsColumns}
                data={sensors}
                pagination
                defaultSortFieldId={1}
                paginationComponentOptions={paginationComponentOptions}
                customStyles={customTableStyles}
                title={'Датчики'}
            />
            <AddEquipmentDialog open={openEquipDialog} onClose={handleCloseEquipDialog} fetchData={fetchData} />
            <AddSensorDialog open={openSensorDialog} onClose={handleCloseSensorDialog} fetchData={fetchData} />
        </div>
    );
};

export default EquipmentPage;
